package com.fancy.application.sys.datasource.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fancy.application.common.controller.BaseController;
import com.fancy.application.common.vo.BasePage;
import com.fancy.application.common.vo.Result;
import com.fancy.application.sys.datasource.config.DataSourceConfig;
import com.fancy.application.sys.datasource.entity.SysDataSourceMain;
import com.fancy.application.sys.datasource.event.DynamicDataSourceRegisterEvent;
import com.fancy.application.sys.datasource.event.DynamicRegisterEvent;
import com.fancy.application.sys.datasource.service.ISysDataSourceMainService;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.sql.DataSource;

import lombok.extern.log4j.Log4j2;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
* fancyCode 自动生成v1.5
* @author wison
* 2022-07-21
* email：wurong715@163.com
*/

@RestController
@RequestMapping("/sys/datasource/sys_data_source_main")
@Log4j2
public class SysDataSourceMainController extends BaseController implements BeanFactoryAware, ApplicationContextAware {

    @Resource
    private ISysDataSourceMainService baseService;

    @PostMapping(value = "/list")
    public Result list(@RequestBody BasePage<SysDataSourceMain> basePage){
        IPage<SysDataSourceMain> sysDataSourceMainPage = baseService.page(basePage.getPage(),basePage.getWrapper());
        return Result.ok(sysDataSourceMainPage);
    }

    @PutMapping
    public Result save(@RequestBody SysDataSourceMain sysDataSourceMain){
        baseService.saveOrUpdate(sysDataSourceMain);
        return Result.ok();
    }
    @DeleteMapping
    public Result del(@RequestParam(required = false) String id ){
        baseService.removeById(id);
        return Result.ok();
    }
    @GetMapping
    public Result view(@RequestParam(required = false) String id ){
        SysDataSourceMain sysDataSourceMain = baseService.getById(id);
        return Result.ok().addData(sysDataSourceMain);
    }
    @PostMapping(value = "/testConnection")
    public Result list(@RequestBody SysDataSourceMain sysDataSourceMain){
        JSONObject resultObj = baseService.testConnection(sysDataSourceMain);
        return Result.ok(resultObj);
    }


    /**
     * 获取当前连接池列表
     * @return
     */
    @GetMapping("/getDataSources")
    public Result getDataSources() {
        List<String> keys = dataSourceConfig.getDataSources();
        return Result.ok().addData(keys);
    }

    /**
     * 获取当前连接池列表
     * @return
     */
    @GetMapping("/testDataSource")
    public Result testDataSource() {
        DataSource ds = dataSourceConfig.getDataSource("38suo");
        JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
        String sql = "select fd_id,doc_subject from sns_group_main";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        return Result.ok(list);
    }

    /**
     * 动态注册数据源
     * @param fdKey
     */
    @PostMapping("/registerDataSource/{fdKey}")
    public Result registerDataSource(@PathVariable String fdKey) {
        if(StrUtil.isEmpty(fdKey)){
            return Result.error("关键字fdKey为空");
        }
        List<SysDataSourceMain> sysDataSourceMains = baseService.lambdaQuery().eq(SysDataSourceMain::getFdKey,fdKey).list();
        if(!sysDataSourceMains.isEmpty()){
            dataSourceConfig.registerDataSource(sysDataSourceMains.get(0));
        }

        return Result.ok("数据源"+fdKey+"创建成功");
    }

    @Resource
    private DataSourceConfig dataSourceConfig;

    private DefaultListableBeanFactory beanFactory;

    private ConfigurableApplicationContext ctx;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        this.ctx = (ConfigurableApplicationContext) ctx;
    }
}
